package com.ruoyi.web.controller.nongjt;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.nongjt.domain.Region;
import com.ruoyi.nongjt.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yunxi
 * 区域信息Controller
 */

@RestController
@RequestMapping("/nongjt/region")
public class RegionController extends BaseController {

    @Autowired
    private RegionService regionService;

    /**
     * 异步加载子区域（支持查询参数）
     */


    @GetMapping("/child/{parentId}")
    public AjaxResult getChildRegions(
            @PathVariable Integer parentId,
            Region region) {
        // 当parentId为-1时，不设置父ID条件（即查询所有符合条件的区域）
        if (parentId != -1) {
            region.setParentId(parentId);
        }
        List<Region> regions = regionService.selectChildRegions(region);
        return AjaxResult.success(regions);
    }

    /**
     * 根据ID查询区域
     */
    @GetMapping("/{id}")
    public AjaxResult getRegionById(@PathVariable Integer id) {
        Region region = regionService.selectRegionById(id);
        return AjaxResult.success(region);
    }

    /**
     * 新增区域
     */
    @PostMapping
    public AjaxResult addRegion(@RequestBody Region region) {
        return toAjax(regionService.insertRegion(region));
    }

    /**
     * 修改区域
     */
    @PutMapping
    public AjaxResult updateRegion(@RequestBody Region region) {
        return toAjax(regionService.updateRegion(region));
    }

    /**
     * 删除单个区域（递归删除所有子区域）
     * @param id 区域ID
     * @return 结果
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Integer id) {
        // 执行递归删除
        int rows = regionService.deleteRegionById(id);
        return toAjax(rows);
    }
}